package httplib;

/**
 * Created by niraymond on 16/8/22.
 */

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class VolleyRequestQueue {
    private static VolleyRequestQueue instance;
//Application Context  保证请求队列在应用程序内全局唯一
    private static Context ctx;

    private RequestQueue queue;
    private ImageLoader imageLoader;

    public static void setApplicationContext(Context applicationContext){
        ctx = applicationContext;
    }

    public static synchronized VolleyRequestQueue getInstance() throws NullPointerException{
        if(ctx == null){
            throw new NullPointerException("请先调用VolleyRequestQueue.setApplicationContext(applicationContext)");
        }
        return getInstance(ctx);
    }

    public static synchronized VolleyRequestQueue getInstance(Context context) {
        if (instance == null) {
            instance = new VolleyRequestQueue(context);
        }
        return instance;
    }

    private VolleyRequestQueue(Context context) {
        ctx = context;
        queue = getRequestQueue();

        imageLoader = new ImageLoader(queue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(20);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }


    public RequestQueue getRequestQueue() {
        if (queue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            queue = Volley.newRequestQueue(ctx.getApplicationContext());
        }
        return queue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }
}
